{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cb6013fe",
   "metadata": {},
   "source": [
    "# 第一节：张量Tensor\n",
    "Tensor是深度学习中最基础的数据类型，可以理解为高维的Matrix，y=(x)中的自变量x。\n",
    "\n",
    "在MindSpore中支持int、list、numpy等数据类型直接转为mindspore.tensor数据类型和推理时将tensor类型转成numpy类型输出。\n",
    "\n",
    "MindSpore编程风格与原生Python保持一致，故可对tensor可进行索引、切片、运算等操作。\n",
    "\n",
    "tensor具有如下属性：\n",
    "![](./微信截图_20220926225313.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "287d2892",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore as ms\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7873c56",
   "metadata": {},
   "source": [
    "## 一、tensor数据类型转换"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77c128d1",
   "metadata": {},
   "source": [
    "### (1)numpy转tensor\n",
    "使用Tensor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "5c6e10cf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]\n",
      " [7 8 9]]\n",
      "<class 'numpy.ndarray'>\n",
      "[[1 2 3]\n",
      " [4 5 6]\n",
      " [7 8 9]]\n",
      "<class 'mindspore.common.tensor.Tensor'>\n"
     ]
    }
   ],
   "source": [
    "arr = np.array([[1, 2, 3],\n",
    "                [4, 5, 6],\n",
    "                [7, 8, 9]])\n",
    "tensor = ms.Tensor(arr)\n",
    "print(arr)\n",
    "print(type(arr))\n",
    "print(tensor)\n",
    "print(type(tensor))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2600d84b",
   "metadata": {},
   "source": [
    "### (2)tensor转numpy\n",
    "使用asnumpy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8bd622b8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]\n",
      " [7 8 9]]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "tf_tensor = tensor.asnumpy()\n",
    "print(tf_tensor)\n",
    "print(type(tf_tensor))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae600055",
   "metadata": {},
   "source": [
    "## 二、用初始化器初始化张量\n",
    "在MindSpore中的initializer中有One(初始化为全1)、Zero(初始化为全0)等API，其他API可在官网文档中查看。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6f5fa824",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 1.]\n",
      " [1. 1.]]\n",
      "<class 'mindspore.common.tensor.Tensor'>\n"
     ]
    }
   ],
   "source": [
    "from mindspore.common.initializer import One\n",
    "# 初识化为全1\n",
    "tensor = ms.Tensor(shape=(2, 2), dtype=ms.float32, init=One())\n",
    "# 注意：此时shape、dtype、init三个参数都要有\n",
    "print(tensor)\n",
    "print(type(tensor))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ca5915c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 0. 0.]\n",
      " [0. 0. 0.]\n",
      " [0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "# 初识化为全0\n",
    "from mindspore.common.initializer import Zero\n",
    "tensor = ms.Tensor(shape=(3, 3), dtype=ms.float32, init=Zero())\n",
    "print(tensor)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f13c8d3a",
   "metadata": {},
   "source": [
    "## 三、继承\n",
    "使用ops中OnesLike操作可继承另一个tensor的属性，形成新的全为1的tensor，同样作用的还有ZerosLike。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "690c6a42",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore.ops as ops"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "59eca88b",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]\n",
      " [1. 1. 1.]]\n",
      "(3, 3)\n"
     ]
    }
   ],
   "source": [
    "oneslike = ops.OnesLike()\n",
    "new_tensor = oneslike(tensor)\n",
    "print(new_tensor)\n",
    "print(new_tensor.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a37ea1c5",
   "metadata": {},
   "source": [
    "## 四、基本运算\n",
    "tensor的基本运算与NumPy的使用方式相似。\n",
    "普通算术运算有：加（+）、减（-）、乘（*）、除（/）、取模（%）、整除（//）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "057ae6de",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]\n",
      " [7 8 9]]\n",
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]\n",
      " [1. 1. 1.]]\n",
      "+: [[ 2.  3.  4.]\n",
      " [ 5.  6.  7.]\n",
      " [ 8.  9. 10.]]\n",
      "*: [[1. 2. 3.]\n",
      " [4. 5. 6.]\n",
      " [7. 8. 9.]]\n",
      "%: [[0. 0. 0.]\n",
      " [0. 0. 0.]\n",
      " [0. 0. 0.]]\n",
      "//: [[1. 2. 3.]\n",
      " [4. 5. 6.]\n",
      " [7. 8. 9.]]\n"
     ]
    }
   ],
   "source": [
    "matrix1 = np.arange(1, 10).reshape((3, 3))\n",
    "matrix2 = np.ones((3, 3))\n",
    "tensor1 = ms.Tensor(matrix1)\n",
    "tensor2 = ms.Tensor(matrix2)\n",
    "print(tensor1)\n",
    "print(tensor2)\n",
    "\n",
    "a = tensor1 + tensor2\n",
    "b = tensor1 * tensor2\n",
    "c = tensor1 % tensor2\n",
    "d = tensor1 // tensor2\n",
    "\n",
    "print(f'+: {a}')\n",
    "print(f'*: {b}')\n",
    "print(f'%: {c}')\n",
    "print(f'//: {d}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f3f5ca3",
   "metadata": {},
   "source": [
    "使用ops中的Concat()和Stack()可将给定维度上的一系列张量连接起来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "8ae34a8d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "shape: (2, 3)\n",
      "[[[1 2 3]]\n",
      "\n",
      " [[4 5 6]]]\n",
      "shape: (2, 1, 3)\n"
     ]
    }
   ],
   "source": [
    "import mindspore.ops as ops\n",
    "tensor1 = ms.Tensor(np.array([[1, 2, 3]]))\n",
    "tensor2 = ms.Tensor(np.array([[4, 5, 6]]))\n",
    "# 上下拼接\n",
    "opC = ops.Concat()\n",
    "# 立体拼接\n",
    "opS = ops.Stack()\n",
    "\n",
    "tensor_new1 = opC((tensor1, tensor2)) \n",
    "tensor_new2 = opS((tensor1, tensor2))\n",
    "# 注意有两个括号\n",
    "\n",
    "print(tensor_new1)\n",
    "print('shape:', tensor_new1.shape)\n",
    "print(tensor_new2)\n",
    "print('shape:', tensor_new2.shape) "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mindspore",
   "language": "python",
   "name": "mindvision"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
